using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace PACKETPARSERMAX20
{
    public static class Support
    {

        public static System.Data.DataTable areaTable = GetAreaTableDataSet();

        internal static System.Data.DataTable GetAreaTableDataSet()
        {
            System.Data.DataTable tAreaTable = new System.Data.DataTable();
            tAreaTable.Columns.Add("id");
            tAreaTable.Columns.Add("mapid");
            tAreaTable.Columns.Add("areatableid");
            tAreaTable.Columns.Add("name");

            System.Xml.XmlDocument tDom = new System.Xml.XmlDocument();
            tDom.Load(AppDomain.CurrentDomain.BaseDirectory + "areatable.xml");
            foreach (System.Xml.XmlElement tAreaXml in tDom.DocumentElement.GetElementsByTagName("area"))
            {
                int tid = int.Parse(tAreaXml.SelectSingleNode("@id").InnerText);
                int tmapid = int.Parse(tAreaXml.SelectSingleNode("@mapid").InnerText);
                int tareatableid = int.Parse(tAreaXml.SelectSingleNode("@areatableid").InnerText);
                string tname = tAreaXml.SelectSingleNode("@name").InnerText;

                tAreaTable.Rows.Add(new object[] { tid, tmapid, tareatableid, tname });

            }
            tAreaTable.PrimaryKey = new System.Data.DataColumn[] { tAreaTable.Columns["id"] };

            return tAreaTable;
        }


        public enum DateInterval
        {
            Second,
            Minute,
            Hour,
            Day,
            Week,
            Month,
            Quarter,
            Year
        }

        public static DateTime Time_T2DateTime(uint time_t)
        {
            long win32FileTime = 10000000 * (long)time_t + 116444736000000000;
            return DateTime.FromFileTimeUtc(win32FileTime).ToLocalTime();
        }

        public static string GetStrFromBR(System.IO.BinaryReader pbr, int pcount)
        {
            char tbBlock;
            StringBuilder tsb = new StringBuilder();
            if (pcount == -1)
            {
                while ((tbBlock = pbr.ReadChar()) != 0)
                    tsb.Append(tbBlock);
            }
            else
            {
                byte[] tChars = new byte[pcount];
                pbr.Read(tChars, 0, pcount);
                for (int i = 0; i < pcount; i++)
                {
                    tbBlock = (char)tChars[i];// pbr.ReadChar();
                    tsb.Append(tbBlock);
                }
            }
            string tVarChar = tsb.ToString();
            return tVarChar;
        }

        public static bool StringCompareUpper(string stringA, string stringB)
        {
            return (string.Compare(stringA, stringB, true,
                 System.Globalization.CultureInfo.CurrentCulture) == 0);
        }

        public static string StringConcatenate(string current, string add)
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder(current);
            builder.Append(add);
            return builder.ToString();
        }

        public static string PadRight(string pValue, int pLength, string pCharacterToAdd)
        {
            string tReturnString = "";

            int tLength = pValue.Length;
            if (tLength < pLength)
            {
                tReturnString = pValue.Trim() + new String(pCharacterToAdd[0], pLength - tLength);
            }
            else
            {
                tReturnString = pValue.Trim().Substring(0, pLength);
            }


            return tReturnString;
        }

        public static string PadLeft(string pValue, int pLength, string pCharacterToAdd)
        {
            int tLength = 0;
            string tReturnString = "";

            tLength = pValue.Length;
            if (tLength < pLength)
            {
                tReturnString = new String(pCharacterToAdd[0], pLength - tLength) + pValue.Trim();
            }
            else
            {
                tReturnString = pValue.Trim().Substring(pValue.Trim().Length - pLength);
            }


            return tReturnString;
        }

        public static DateTime BeginningOfWeek(DateTime ForWhichDate)
        {
            return ForWhichDate.AddDays(-((int)ForWhichDate.DayOfWeek));
        }

        public static DateTime BeginningOfPreviousWeek(DateTime ForWhichDate)
        {
            return ForWhichDate.AddDays(-((int)ForWhichDate.DayOfWeek)).AddDays(-6);
        }

        public static DateTime EndOfWeek(DateTime ForWhichDate)
        {
            return ForWhichDate.AddDays(((int)ForWhichDate.DayOfWeek));
        }

        public static long DateDiff(DateInterval Interval, System.DateTime StartDate, System.DateTime EndDate)
        {
            long lngDateDiffValue = 0;
            System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
            switch (Interval)
            {
                case DateInterval.Day:
                    lngDateDiffValue = (long)TS.Days; break;
                case DateInterval.Hour:
                    lngDateDiffValue = (long)TS.TotalHours; break;
                case DateInterval.Minute:
                    lngDateDiffValue = (long)TS.TotalMinutes; break;
                case DateInterval.Month:
                    lngDateDiffValue = (long)(TS.Days / 30); break;
                case DateInterval.Quarter:
                    lngDateDiffValue = (long)((TS.Days / 30) / 3); break;
                case DateInterval.Second:
                    lngDateDiffValue = (long)TS.TotalSeconds; break;
                case DateInterval.Week:
                    lngDateDiffValue = (long)(TS.Days / 7); break;
                case DateInterval.Year:
                    lngDateDiffValue = (long)(TS.Days / 365); break;
            }
            return (lngDateDiffValue);
        }

        public static bool IsDate(object pValue)
        {

            if (IsEmpty(pValue))
            {
                return false;
            }
            else
            {
                DateTime tOutDate;
                return DateTime.TryParse(pValue.ToString().Trim(), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out tOutDate);
            }
        }

        public static bool IsEmpty(object Value)
        {
            bool tIsEmpty = false;
            if (Value == null || string.Empty.Equals(Value) || DBNull.Value.Equals(Value))
            {
                tIsEmpty = true;
            }
            else
            {
                tIsEmpty = Value.ToString().Length == 0;
            }
            return tIsEmpty;
        }

        public static bool IsNumeric(object pValue)
        {
            if (pValue == null)
            {
                return false;

            }
            else
            {
                double tOutValue;
                return double.TryParse(pValue.ToString().Trim(),
                    System.Globalization.NumberStyles.Any,
                    System.Globalization.CultureInfo.CurrentCulture,
                    out tOutValue);
            }
        }

        public static int Asc(char pChar)
        {
            //Return the character value of the given character
            return (int)Encoding.ASCII.GetBytes(new char[] { pChar })[0];
        }

        public static string CStr(object pValue)
        {
            if (IsEmpty(pValue))
            {
                return "";
            }
            else
            {
                return pValue.ToString();
            }
        }

        public static string CStr(object pValue, int pMaxLength)
        {

            if (IsEmpty(pValue))
            {
                return "";
            }
            else
            {
                string tString = pValue.ToString();
                if (tString.Length > pMaxLength)
                {
                    return tString.Substring(0, pMaxLength);
                }
                else
                {
                    return tString;
                }
            }
        }

        public static System.DateTime CDate(object pValue)
        {
            if (!IsDate(pValue))
            {
                return System.DateTime.MinValue;
            }
            else
            {
                DateTime tOutDate;
                DateTime.TryParse(pValue.ToString().Trim(), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out tOutDate);
                return tOutDate;
            }
        }

        public static int CInt(object pValue)
        {

            int tReturn = 0;
            if (pValue == null)
            {
                return (int)tReturn;

            }
            else
            {
                int.TryParse(pValue.ToString(), out tReturn);
                //Double.TryParse(pValue.ToString(),  System.Globalization.NumberStyles.Integer & NumberStyles.AllowCurrencySymbol  , System.Globalization.CultureInfo.CurrentCulture, out tReturn);
                return tReturn;
            }
        }

        public static long CLng(object pValue)
        {

            long tReturn = 0;
            if (pValue == null)
            {
                return tReturn;

            }
            else
            {
                long.TryParse(pValue.ToString(), out tReturn);
                //Double.TryParse(pValue.ToString(),  System.Globalization.NumberStyles.Integer & NumberStyles.AllowCurrencySymbol  , System.Globalization.CultureInfo.CurrentCulture, out tReturn);
                return tReturn;
            }
        }

        public static float CFloat(object pValue)
        {

            double tReturn = 0;
            if (pValue == null)
            {
                return (float)tReturn;

            }
            else
            {
                Double.TryParse(pValue.ToString(), NumberStyles.Float & NumberStyles.AllowCurrencySymbol, System.Globalization.CultureInfo.CurrentCulture, out tReturn);
                return (float)tReturn;
            }
        }

        public static double CDbl(object pValue)
        {
            double tReturn = 0;
            if (pValue == null)
            {
                return tReturn;

            }
            else
            {
                Double.TryParse(pValue.ToString(), NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out tReturn);
                return tReturn;
            }
        }

        public static string GetDBString(string pValue)
        {
            if (IsEmpty(pValue))
            {
                return " NULL ";
            }
            else
            {
                return "'" + pValue.ToString().Replace("'", "''") + "'";
            }
        }

        public static string GetDBString(string pValue, int pMaxLength)
        {
            if (IsEmpty(pValue))
            {
                return " NULL ";
            }
            else
            {
                string tString = pValue;
                if (tString.Length > pMaxLength)
                {
                    return "'" + tString.Substring(0, pMaxLength).Replace("'", "''") + "'";
                }
                else
                {
                    return "'" + tString.Replace("'", "''") + "'";
                }

            }
        }

        public static string GetDBNumber(object pValue)
        {
            if (!IsNumeric(pValue.ToString()))
            {
                return " NULL ";
            }
            else
            {

                return pValue.ToString();

            }
        }

        public static string GetDBDate(object pValue)
        {
            if (CDate(pValue) == System.DateTime.MinValue)
            {
                return " NULL ";
            }
            else
            {

                return "'" + pValue.ToString() + "'";

            }
        }

        public static uint GetUInt(this object pValue)
        {
            if (pValue == DBNull.Value)
                return 0;

            if (pValue == null)
                return 0;

            uint tOut = 0;

            if (uint.TryParse(pValue.ToString(), out tOut))
                return tOut;

            return 0;
        }

        public static int GetInt(this object pValue)
        {
            if (pValue == DBNull.Value)
                return 0;

            if (pValue == null)
                return 0;

            int tOut = 0;

            if (int.TryParse(pValue.ToString(), out tOut))
                return tOut;

            return 0;
        }

        public static void Execute(string pFileName, string pCommandLine)
        {
            string tBatch = System.AppDomain.CurrentDomain.BaseDirectory + Guid.NewGuid().ToString() + "_run.bat";

            string tArgs = string.Format(" \"{0}\" ", pFileName);
            StringBuilder tsb = new StringBuilder();
            tsb.AppendLine(pCommandLine + tArgs);

            //tsb.AppendLine("pause");

            //tsb.AppendLine(string.Format("\r\n del \"{0}\"", tBatch));

            System.IO.File.WriteAllText(tBatch, tsb.ToString());
            ExecuteBatch(tBatch, true);
            System.IO.File.Delete(tBatch);
        }

        public static string ExecuteBatch(string pBatchFilePath, bool pWaitForBatchCompletion)
        {
            string tExceptionMsg = "";

            System.Diagnostics.Process tProc = new System.Diagnostics.Process();

            try
            {
                tProc.StartInfo.UseShellExecute = true;
                tProc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                tProc.StartInfo.FileName = pBatchFilePath;
                tProc.Start();
                if (pWaitForBatchCompletion) { tProc.WaitForExit(); }
                System.IO.File.Delete(pBatchFilePath);
            }
            catch (Exception ex)
            {
                if (tProc != null) { tProc.Kill(); }

                tExceptionMsg += ex.Message + "\r\n";


            }

            return tExceptionMsg;
        }
    }

    public class Converter
    {
        public static UInt32 ToUInt32(byte[] d, ref int offset)
        {
            UInt32 i = BitConverter.ToUInt32(d, offset);
            offset += 4;
            return i;
        }
        public static UInt64 ToUInt64(byte[] d, ref int offset)
        {
            UInt64 i = BitConverter.ToUInt64(d, offset);
            offset += 8;
            return i;
        }
        public static Int32 ToInt32(byte[] d, ref int offset)
        {
            Int32 i = BitConverter.ToInt32(d, offset);
            offset += 4;
            return i;
        }
        public static Int64 ToInt64(byte[] d, ref int offset)
        {
            Int64 i = BitConverter.ToInt64(d, offset);
            offset += 8;
            return i;
        }
        public static float ToFloat(byte[] d, ref int offset)
        {
            Single i = BitConverter.ToSingle(d, offset);
            offset += 4;
            return i;
        }
        public static double ToDouble(byte[] d, ref int offset)
        {
            double i = BitConverter.ToDouble(d, offset);
            offset += 8;
            return i;
        }
        public static UInt16 ToUInt16(byte[] d, ref int offset)
        {
            UInt16 i = BitConverter.ToUInt16(d, offset);
            offset += 2;
            return i;
        }
        public static Int16 ToInt16(byte[] d, ref int offset)
        {
            Int16 i = BitConverter.ToInt16(d, offset);
            offset += 2;
            return i;
        }
        public static byte ToByte(byte[] d, ref int offset)
        {
            return d[offset++];
        }
        public static void ToBytes(object a, byte[] b, ref int t)
        {
            if (a is int)
                ToBytes((int)a, b, ref t);
            if (a is uint)
                ToBytes((uint)a, b, ref t);
            else
                if (a is UInt64)
                    ToBytes((UInt64)a, b, ref t);
                else
                    if (a is Int64)
                        ToBytes((Int64)a, b, ref t);
                    else
                        if (a is UInt16)
                            ToBytes((UInt16)a, b, ref t);
                        else
                            if (a is Int16)
                                ToBytes((Int16)a, b, ref t);
                            else
                                if (a is byte)
                                    ToBytes((byte)a, b, ref t);
                                else
                                    if (a is string)
                                        ToBytes((string)a, b, ref t);
        }
        public static void ToBytes(int a, byte[] b, ref int t)
        {
            b[t++] = (byte)((a) & 0xff);
            b[t++] = (byte)((a >> 8) & 0xff);
            b[t++] = (byte)((a >> 16) & 0xff);
            b[t++] = (byte)((a >> 24) & 0xff);
        }
        public static void ToBytes(System.Collections.BitArray a, byte[] b, ref int t)
        {
            a.CopyTo(b, t);
            t += a.Length / 8;
        }
        public static void ToBytes(System.Collections.BitArray a, byte[] b, ref int t, int len)
        {
            a.CopyTo(b, t);
            t += len;
        }
        public static void ToBytes(string a, byte[] b, ref int t)
        {
            char[] s = a.ToCharArray();
            foreach (char c in s)
                b[t++] = (byte)c;
        }
        public static void ToBytes(uint a, byte[] b, ref int t)
        {
            b[t++] = (byte)((a) & 0xff);
            b[t++] = (byte)((a >> 8) & 0xff);
            b[t++] = (byte)((a >> 16) & 0xff);
            b[t++] = (byte)((a >> 24) & 0xff);
            //byte []temp = BitConverter.GetBytes( a );
            //Buffer.BlockCopy( temp, 0, b, t, temp.Length );
            //t += temp.Length;
        }
        public static void ToBytes(UInt64 a, byte[] b, ref int t)
        {
            /*
            byte []temp = BitConverter.GetBytes( a );
            Buffer.BlockCopy( temp, 0, b, t, temp.Length );
            t += temp.Length;*/

            b[t++] = (byte)((a) & 0xff);
            b[t++] = (byte)((a >> 8) & 0xff);
            b[t++] = (byte)((a >> 16) & 0xff);
            b[t++] = (byte)((a >> 24) & 0xff);
            b[t++] = (byte)((a >> 32) & 0xff);
            b[t++] = (byte)((a >> 40) & 0xff);
            b[t++] = (byte)((a >> 48) & 0xff);
            b[t++] = (byte)((a >> 56) & 0xff);
        }
        public static void ToBytes(Int64 a, byte[] b, ref int t)
        {
            ToBytes((UInt64)a, b, ref t);
        }
        public static void ToBytes(float a, byte[] b, ref int t)
        {
            byte[] temp = BitConverter.GetBytes(a);
            Buffer.BlockCopy(temp, 0, b, t, temp.Length);
            t += temp.Length;
        }
        public static void ToBytes(double a, byte[] b, ref int t)
        {
            byte[] temp = BitConverter.GetBytes(a);
            Buffer.BlockCopy(temp, 0, b, t, temp.Length);
            t += temp.Length;
        }
        public static void ToBytes(UInt16 a, byte[] b, ref int t)
        {
            /*byte []temp = BitConverter.GetBytes( a );
            Buffer.BlockCopy( temp, 0, b, t, temp.Length );
            t += temp.Length;*/
            b[t++] = (byte)((a) & 0xff);
            b[t++] = (byte)((a >> 8) & 0xff);
        }
        public static void ToBytes(Int16 a, byte[] b, ref int t)
        {/*
			byte []temp = BitConverter.GetBytes( a );
			Buffer.BlockCopy( temp, 0, b, t, temp.Length );
			t += temp.Length;*/
            b[t++] = (byte)((a) & 0xff);
            b[t++] = (byte)((a >> 8) & 0xff);

        }
        public static void ToBytes(byte a, byte[] b, ref int t)
        {
            b[t++] = a;
        }
    }
}
